﻿using Awsc.DataAcquisitionSys.Api.Models;
using Awsc.DataAcquisitionSys.Api.SingalRServices;
using Awsc.DataAcquisitionSys.Core.DataAcquisition;
using Awsc.DataAcquisitionSys.Core.Models.ServiceModels;
using Awsc.DataAcquisitionSys.Core.Services.ConfigManagement;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using System.Text;


namespace Awsc.DataAcquisitionSys.Api.BackgroundServices
{
    public class PushSensorDataService : BackgroundService
    {
        private readonly IHubContext<SensorDataHub> _hubContext;
        private readonly IDeviceConfigService deviceConfigService;
        private readonly IConfiguration configuration;

        private const int PushInterval = 200; // Interval in milliseconds

        public PushSensorDataService(IHubContext<SensorDataHub> hubContext, IDeviceConfigService deviceConfigService)
        {
            _hubContext = hubContext;
            this.deviceConfigService = deviceConfigService;
        }

        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {

            using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(PushInterval));
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await timer.WaitForNextTickAsync(stoppingToken);

                    var deviceConfig = deviceConfigService.GetDeviceConfig();
                    SensorDataResponse response = new SensorDataResponse();


                    //GlobalDeviceManager.Instance
                    var allSensors = deviceConfig.GetAllSensorConfig();

                    var reportConfigString = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "DataReportConfig.json"), Encoding.UTF8);
                    var reportConfigs = JsonConvert.DeserializeObject<List<ReportDataConfig>>(reportConfigString);

                    allSensors = allSensors.Where(s => reportConfigs.Any(r => r.Key == s.Name)).ToList();

                    var powerSensors = allSensors.Where(s => s.CollectorName.Contains("动力源采集柜")).ToList();

                    var remoteControlHouseSensors = allSensors.Where(s => s.CollectorName.Contains("远控房")).ToList();

                    var mainHostSensors = allSensors.Except(powerSensors).Except(remoteControlHouseSensors).ToList();

                    NamedSensorDataCollection powerHouseCollection = new NamedSensorDataCollection("动力源");
                    response.NamedSensorDataCollections.Add(powerHouseCollection);

                    foreach (var sensor in powerSensors)
                    {
                        var s = GetSensorData(sensor.Name);
                        if (s != null)
                        {
                            powerHouseCollection.Sensors.Add(s);
                        }
                    }
                    NamedSensorDataCollection remoteControlHouseCollection = new NamedSensorDataCollection("远控房");
                    response.NamedSensorDataCollections.Add(remoteControlHouseCollection);


                    foreach (var sensor in remoteControlHouseSensors)
                    {
                        var s = GetSensorData(sensor.Name);
                        if (s != null)
                        {
                            remoteControlHouseCollection.Sensors.Add(s);
                        }

                    }
                    NamedSensorDataCollection mainHostCollection = new NamedSensorDataCollection("主机设备");
                    response.NamedSensorDataCollections.Add(mainHostCollection);

                    foreach (var sensor in mainHostSensors)
                    {

                        var s = GetSensorData(sensor.Name);
                        if (s.Name == "管柱下深")
                        {

                        }
                        if (s != null)
                        {
                            mainHostCollection.Sensors.Add(s);
                        }
                    }

                    var unsupportLength = deviceConfig.MaxUnsurportLength;

                    SensorData unsupportLengthSensor = new SensorData();
                    unsupportLengthSensor.Status = DevStatus.S_OK;
                    unsupportLengthSensor.Name = "无支持长度";
                    unsupportLengthSensor.Value = unsupportLength;
                    unsupportLengthSensor.Unit = "m";
                    mainHostCollection.Sensors.Add(unsupportLengthSensor);


                    var json = JsonConvert.SerializeObject(response);

                    await _hubContext.Clients.All.SendAsync("ReceiveSensorData", response);
                }
                catch (TaskCanceledException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    await Task.Delay(1000, stoppingToken);
                }
            }
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }

        private  SensorData GetSensorData(string sensorName)
        {

            var sensorData = GlobalDeviceManager.Instance.GetSensorValue(sensorName);
            if(sensorData!=null)
            {
                return sensorData;
            }

            var sensorConfig = deviceConfigService.GetDeviceConfig().GetAllRegisterConfigs().FirstOrDefault(s => s.Name == sensorName);
            if(sensorConfig==null)
            {
                return null;
            }

            SensorData s = new SensorData();
            s.Name = sensorName;
            s.Value = null;
            s.Status = DevStatus.S_UNKNOWN;
            if(sensorConfig.IsCoil)
            {
                s.Unit = "打开，关闭";
            }
            else
            {
                s.Unit = sensorConfig.RangeUnit;
            }
            return s;
        }


    }
}
